/*
 * @Author: hupaocai 13767071930@163.com
 * @Date: 2025-03-27 17:28:47
 * @LastEditors: hupaocai 13767071930@163.com
 * @LastEditTime: 2025-03-28 11:43:34
 * @FilePath: /banban-front/utils/request.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { getToken } from '@/utils/auth'
import { toast, showConfirm, tansParams } from '@/utils/common'

const timeout = 10000
const baseUrl = 'http://120.26.249.59:8080'

const apiServer = baseUrl

const request = config => {
    if (config.loading !== false) {
        uni.showLoading({
            title: '',
            mask: true,
        })
    }
    // 是否需要设置 token
    const noToken = (config.headers || {}).isToken === false
    const timeStamp = new Date().getTime();
    if (getToken() && !noToken) {
        config.headers['Authorization'] = 'Bearer ' + getToken()
    }

    // get请求映射params参数
    if (config.params) {
        let url = `${config.url}?${tansParams(config.params)}`
        url = url.slice(0, -1)
        config.url = url
    }
    const params = {
        uri: config.url,
        param: { ...config.data }
    }

    console.log('请求参数:', params)
   
    return new Promise((resolve, reject) => {
        uni.request({
            method: config.method || 'get',
            timeout: config.timeout || timeout,
            url: apiServer + config.url,
            data: { ...config.data },
            header: config.headers,
        }).then(response => {
            console.log( '响应参数：', response)
            const { data: { code }, statusCode } = response

            // TODO: 特殊处理手机登录接口
            // const whiteNoLogin = ['mp/api/auth/loginByPhone', 'mp/api/auth/login']
            // !whiteNoLogin.includes(config.url) && 
            if (code === 401) {
                uni.navigateTo({ url: '/pages/login/index' })
                return
            }

            // 状态成功
            if (statusCode === 200) {
                resolve(response.data)
                return
            }

            // 状态失败
            reject(response)
        })
        .catch(error => {
            
            reject(error)
        }).finally(_ => {
            if (config.loading !== false) {
                uni.hideLoading()
            }
        })
    })
}
export default request